function [a,P] =GetOpen(P,S,mode)
    
    B=S{1};

    P_X=P{1}(1);
    P_Y=P{1}(2);
    %P_theta=P{1}(3);
    %P_pace = P{5};
    P_num = P{3};

    B_X=B{1}(1);
    B_Y=B{1}(2);
    %angle=0;
    
    player_to_ball =sqrt((B_X-P_X)^2+(B_Y-P_Y)^2); % distance between player and ball
    %angle=atan2(B_Y-P_Y,B_X-P_X)/pi*180;    %compute the angle to the ball in degrees
    
target = LoadTarget(P);

if (isempty(target))
    [a,P] = SelectNewTarget(P,S,mode);
else
    Target_X = target(1);
    Target_Y = target(2);
    target_to_ball = euc_dist(B_X, B_Y, Target_X, Target_Y);

    if (Target_X + 10 > B_X && target_to_ball > 10 && target_to_ball < 40 && euc_dist(P_X,P_Y,Target_X,Target_Y)>3)
        [a, P] = GoToLocation(P,S,mode, Target_X, Target_Y);
    else
        [a,P] = SelectNewTarget(P,S,mode);
    end
end

end

function [a,P] = SelectNewTarget(P,S,mode)

P_X=P{1}(1);
P_Y=P{1}(2);
P_num = P{3};

B=S{1};
B_X=B{1}(1);
B_Y=B{1}(2);

if(P{2} == 'r')
    Target_X = B_X + round(rand_num(-10, 30));
    %if(P_Y >= B_Y)
    if(rand(1)<=0.5)    
        Target_Y = B_Y + round(rand_num(10, 30));
    else
        Target_Y = B_Y + round(rand_num(-10, -30));
    end  
else
    Target_X = B_X + round(rand_num(-30, 10));
    %if(P_Y >= B_Y)
    if(rand(1)<=0.5)    
        Target_Y = B_Y + round(rand_num(10, 30));
    else
        Target_Y = B_Y + round(rand_num(-10, -30));
    end
end

SaveTarget(P,[Target_X, Target_Y]);
[a, P] = GoToLocation(P,S,mode, Target_X, Target_Y);

end